import datetime
import random

from django.db import models


from sportsground.utils.baseModels import BaseModels, IntegerChoices


class OrderYard(BaseModels):
    class Meta():
        db_table = 'order_yard'
        verbose_name = '订场订单'
        verbose_name_plural = verbose_name

    class State(IntegerChoices):
        Paying = 1, "待支付"
        PayTimeout = 2, "未支付-交易关闭"
        Payed_Checking = 3, "支付成功-未核验"
        Payed_Checked = 4, "订单完成-已核验"
        Drawback = 5, "退款"

    order = models.ForeignKey(to="Order", on_delete=models.CASCADE, verbose_name="总订单")
    yard = models.ForeignKey(to="Venue.VenueSportYard", on_delete=models.CASCADE, verbose_name="订场")
    state = models.IntegerField(choices=State.choices, default=State.Paying, verbose_name="状态")

    date = models.DateField(verbose_name="预约日期")
    startTime = models.TimeField(verbose_name="预约开始时间")
    endTime = models.TimeField(verbose_name="预约结束时间")

    price = models.FloatField(verbose_name="价格")
    number = models.IntegerField(verbose_name="数量")
    verify = models.IntegerField(null=True, verbose_name="校验码")
    getTime = models.DateTimeField(null=True, verbose_name="收货时间")
    message = models.CharField(max_length=200, verbose_name="留言")

    drawback = models.ForeignKey(to="Drawback", null=True, on_delete=models.CASCADE, verbose_name="退款")

    @classmethod
    def getVerify(cls):
        """ 获取校验码 """
        return random.randint(1000, 9999)

    @classmethod
    def create(cls, user, yard, date, time, number=1, message=''):
        """ 创建 """
        from User.models import Order

        venue = yard.venueSport.venue
        order = Order.create(user, venue, Order.OrderType.Yard)
        orderYard = cls(order=order, yard=yard, state=cls.State.Paying,
                        date=date, startTime=time.startTime, endTime=time.endTime,
                        price=time.price, number=number, verify=None,
                        message=message)
        orderYard.save()
        return order

    def capitalInfo(self):
        """ 资金流水账 """
        return {
            "oid": self.order_id,
            "id": self.id,
            "yardId": self.yard_id,
            "price": self.price,
            "number": self.number,
            "createTime": self.createTime
        }

    def Info(self):
        self.checkTimeout()
        return {
            "id": self.id,
            "yard": self.yard.Info(),
            "state": self.state,
            "date": self.date,
            "startTime": self.startTime,
            "endTime": self.endTime,
            "price": self.price,
            "number": self.number,
            "verify": self.verify,
            "getTime": self.getTime,
            "message": self.message,
            "drawback": self.drawback.Info() if self.drawback else None,
            "createTime": self.createTime,
        }

    def pay(self):
        """ 支付 """
        if self.state == self.State.Paying:
            self.state = self.State.Payed_Checking
            self.verify = self.getVerify()
            self.save()

    def checkTimeout(self):
        """ 超时 """
        if self.state == self.State.Paying:
            over = self.createTime + datetime.timedelta(minutes=30)
            now = datetime.datetime.now()
            if over < now:
                self.state = self.State.PayTimeout
                self.save()

    def verifyCode(self, verifyCode=''):
        """ 订单校验码 """
        if self.state== self.State.Payed_Checking and verifyCode == self.verify:
            self.state = self.State.Payed_Checked
            self.getTime = datetime.datetime.now()
            self.save()
            return True
        return False

    def canDrawback(self):
        """ 是否能退款 """
        if self.state in [
            self.State.Payed_Checking,
            self.State.Payed_Checked,
        ]:
            return True
        return False

    def orderDrawback(self, user, price, message):
        """ 场地订单退款 """
        from User.models import Drawback

        self.state = self.State.Drawback
        self.save()
        Drawback.create(user=user, price=price, message=message)
